#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDebug>
#include <QGraphicsRectItem>
#include <QGraphicsEllipseItem>
#include <QInputDialog>
#include <QColorDialog>
#include <QFontDialog>
#include <QTime>
#include <QKeyEvent>
#include <QQueue>

template<class T> void setBrushColor(T *item)
{//函数模板
    QColor color=item->brush().color();
    color=QColorDialog::getColor(color,NULL,"选择填充颜色");
    if (color.isValid())
        item->setBrush(QBrush(color));
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 设置背景图片为bj.jpg
    this->setObjectName("MainWindow");
    this->setStyleSheet("#MainWindow{border-image:url(:/res/background.jpeg);}");
    QStatusBar *sBar = statusBar();//
    Protocal_Version =  new QLabel(this);
    Protocal_Version->setMinimumSize(100, 20);
    Protocal_Version->setText("当前协议：   ");
    sBar->addPermanentWidget(Protocal_Version);
    mySerialPort = new QSerialPort(this);
    // 串口接收，信号槽关联
    connect(mySerialPort, SIGNAL(readyRead()), this, SLOT(serialPortRead_Slot()));

    scene=new QGraphicsScene(-230,-50,460,100); //创建QGraphicsScene

    ui->View->setScene(scene); //与view关联
    ui->View->setAttribute(Qt::WA_TranslucentBackground, true);

    //关闭信号槽 固定界面
//    QObject::connect(ui->View,SIGNAL(mouseMovePoint(QPoint)),
//                     this, SLOT(on_mouseMovePoint(QPoint)));

//    QObject::connect(ui->View,SIGNAL(mouseClicked(QPoint)),
//                     this, SLOT(on_mouseClicked(QPoint)));

//    QObject::connect(ui->View,SIGNAL(mouseDoubleClick(QPoint)),
//                     this, SLOT(on_mouseDoubleClick(QPoint)));

//    QObject::connect(ui->View,SIGNAL(keyPress(QKeyEvent*)),
//                     this, SLOT(on_keyPress(QKeyEvent*)));

    add_Rects() ;
    add_Circles();
    add_Text();
    add_Polygon();
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::protocal_handle(QByteArray recBuf)
{

        uchar b1;
        uchar b2;

        for (int loop_i=0;loop_i<recBuf.count();loop_i++) {

            // qDebug()<<recBuf;
            if(loop_i+5 >(recBuf.count()-1))return;
            if((recBuf.at(loop_i)==0x55)&&((uchar)recBuf.at(loop_i+5)==0xaa))
            {
                switch (recBuf.at(2))
                {
                    case 0x01:Protocal_Version->setText("当前协议：博远");break;
                    case 0x02:Protocal_Version->setText("当前协议：海康");break;
                    case 0x03:Protocal_Version->setText("当前协议：大华");break;
                }

                break;
            }
        }
        b1=recBuf.at(3)&0x0f;
        b2=recBuf.at(4)&0xff;


        char16_t b3 = b1*256+b2;
        QList<QPointF> pointslist;
        QList<QGraphicsEllipseItem *>theItem;
        pointslist.append(QPointF(-209,8));
        pointslist.append(QPointF(-174,3));
        pointslist.append(QPointF(-155,8));
        pointslist.append(QPointF(-86,6));
        pointslist.append(QPointF(-56,7));
        pointslist.append(QPointF(-33,8));
        pointslist.append(QPointF(31 ,10));
        pointslist.append(QPointF(65 ,5));
        pointslist.append(QPointF(83 ,7));
        pointslist.append(QPointF(150,7));
        pointslist.append(QPointF(187,5));
        pointslist.append(QPointF(218,10));

        for (int i=0;i<pointslist.count();i++)
         {
            theItem.append(qgraphicsitem_cast<QGraphicsEllipseItem*>(scene->itemAt(pointslist.at(i),ui->View->transform())));
         }

        for (int i=pointslist.count();i>0;i--)
        {
            if(b3&0x0001)
                 theItem.at(i-1)->setBrush(Qt::gray);
             else
                theItem.at(i-1)->setBrush(Qt::red);
            b3=b3>>1;
        }

}


void MainWindow::serialPortRead_Slot()
{
    static bool head_flag = false;
    static bool tail_flag = false;
    static int i= 0,j=0;
    static QByteArray buf,buf_t;
    buf.clear();
    //buf_t.clear();
    buf = mySerialPort->readAll();
    for(i = 0;i<buf.length();i++)
    {
        if(0x55 == (uchar)buf.at(i))
        {
            head_flag = true;
            tail_flag = false;
        }
        if(0xAA == (uchar)buf.at(i))
            tail_flag = true;

        if(head_flag)
            buf_t[j++] =buf[i];
        if(tail_flag && head_flag)
        {
            qDebug()<<buf_t;
            protocal_handle(buf_t);
            j = 0;
            buf_t.clear();
            head_flag = false;
        }
    }
    buf.clear();


}
//void MainWindow::serialPortRead_Slot()
//{
//     uchar type =  0;
//     uchar b1 = 0xff;
//     uchar b2 = 0xff;
//     char16_t res= 0;
//     QByteArray recBuf;
//     recBuf.clear();
//     recBuf = mySerialPort->readAll();//这里谨记

//      for (int loop_i=0;loop_i<recBuf.count();loop_i++)
//        {
//            if(loop_i+3 <=(recBuf.count()-1))
//            {
//                if(recBuf.at(loop_i)==0x01)
//                {
//                    res += recBuf.at(loop_i);
//                    res += recBuf.at(loop_i+1);
//                    res += recBuf.at(loop_i+2);
//                    res =res&0x00ff;
//                    if(res==(uchar)recBuf.at(loop_i+3))
//                    {
//                        Protocal_Version->setText("当前协议：博远");
//                        type = 1;
//                        b1=recBuf.at(1)&0x0f;
//                        b2=recBuf.at(2)&0xff;
//                    }
//                    break;
//                }
//            }
//        }

//if(type == 0)
//{
//    for (int loop_i=0;loop_i<recBuf.count();loop_i++) {

//         qDebug()<<recBuf.count();
//        if(loop_i+5 >(recBuf.count()-1))return;
//        if((recBuf.at(loop_i)==0x55)&&((uchar)recBuf.at(loop_i+5)==0xaa))
//        {
//            switch (recBuf.at(2))
//            {
//                case 0x01:Protocal_Version->setText("当前协议：博远");break;
//                case 0x02:Protocal_Version->setText("当前协议：海康");break;
//                case 0x03:Protocal_Version->setText("当前协议：大华");break;
//            }

//            break;
//        }
//    }
//    b1=recBuf.at(3)&0x0f;
//    b2=recBuf.at(4)&0xff;
// }

//    char16_t b3 = b1*256+b2;
//    QList<QPointF> pointslist;
//    QList<QGraphicsEllipseItem *>theItem;
//    pointslist.append(QPointF(-209,8));
//    pointslist.append(QPointF(-174,3));
//    pointslist.append(QPointF(-155,8));
//    pointslist.append(QPointF(-86,6));
//    pointslist.append(QPointF(-56,7));
//    pointslist.append(QPointF(-33,8));
//    pointslist.append(QPointF(31 ,10));
//    pointslist.append(QPointF(65 ,5));
//    pointslist.append(QPointF(83 ,7));
//    pointslist.append(QPointF(150,7));
//    pointslist.append(QPointF(187,5));
//    pointslist.append(QPointF(218,10));

//    for (int i=0;i<pointslist.count();i++)
//     {
//        theItem.append(qgraphicsitem_cast<QGraphicsEllipseItem*>(scene->itemAt(pointslist.at(i),ui->View->transform())));
//     }

//    for (int i=pointslist.count();i>0;i--)
//    {
//        if(b3&0x0001)
//             theItem.at(i-1)->setBrush(Qt::gray);
//         else
//            theItem.at(i-1)->setBrush(Qt::red);
//        b3=b3>>1;
//    }


//}

void MainWindow::send_data(QString str)
{
     QByteArray read_protocal_version = QByteArray::fromHex("550102AA");
     read_protocal_version.toHex(' ');
     mySerialPort->write(read_protocal_version);

}

void MainWindow::on_connect_btn_clicked()
{

    QSerialPort::BaudRate baudRate=  QSerialPort::Baud9600;
    QSerialPort::DataBits dataBits=  QSerialPort::Data8;
    QSerialPort::StopBits stopBits=  QSerialPort::OneStop;
    QSerialPort::Parity   checkBits= QSerialPort::NoParity;

    // 想想用 substr strchr怎么从带有信息的字符串中提前串口号字符串
    // 初始化串口属性，设置 端口号、波特率、数据位、停止位、奇偶校验位数
    mySerialPort->setBaudRate(baudRate);
    mySerialPort->setDataBits(dataBits);
    mySerialPort->setStopBits(stopBits);
    mySerialPort->setParity(checkBits);
    //mySerialPort->setPortName(ui->cmbSerialPort->currentText());// 不匹配带有串口设备信息的文本
    // 匹配带有串口设备信息的文本
    QString spTxt =     ui->comboBox->currentText();

    spTxt = spTxt.section(':', 0, 0);//spTxt.mid(0, spTxt.indexOf(":"));
    qDebug() << spTxt;
    mySerialPort->setPortName(spTxt);

    // 根据初始化好的串口属性，打开串口
    // 如果打开成功，反转打开按钮显示和功能。打开失败，无变化，并且弹出错误对话框。
    if(ui->connect_btn->text() == "打开串口"){
        if(mySerialPort->open(QIODevice::ReadWrite) == true){

            //send data
            mySerialPort->flush();
           // send_data("reply_to_client connect\r\n");
            send_data("0x55 0x01 0x02 0xAA");
            ui->connect_btn->setText("关闭串口");
            // 让端口号下拉框不可选，避免误操作（选择功能不可用，控件背景为灰色）
            ui->comboBox->setEnabled(false);

        }else{
            QMessageBox::critical(this, "错误提示", "串口连接失败！！！\r\n该串口可能被占用\r\n请选择正确的串口");

        }
    }else{
        mySerialPort->close();
        ui->connect_btn->setText("打开串口");
        Protocal_Version->setText("当前协议：   ");
        // 端口号下拉框恢复可选，避免误操作
        ui->comboBox->setEnabled(true);
    }
}

void MainWindow::on_mouseMovePoint(QPoint point)
{

}

void MainWindow::on_mouseClicked(QPoint point)
{

}

void MainWindow::on_mouseDoubleClick(QPoint point)
{
    QPointF pointScene=ui->View->mapToScene(point); //转换到Scene坐标

    QGraphicsItem  *item=NULL;
    item=scene->itemAt(pointScene,ui->View->transform()); //获取光标下的绘图项
    qDebug()<<item->Type;
    if (item == NULL) //没有绘图项
        return;

    switch (item->type())  //绘图项的类型
    { //
      case    QGraphicsRectItem::Type: //矩形框
      { //强制类型转换
        QGraphicsRectItem *theItem=qgraphicsitem_cast<QGraphicsRectItem*>(item);
        setBrushColor(theItem);
        break;
      }
      case    QGraphicsEllipseItem::Type: //椭圆和圆都是 QGraphicsEllipseItem
      {
         qDebug()<<pointScene;
        QGraphicsEllipseItem *theItem;
        theItem=qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
        setBrushColor(theItem);
        break;
      }

      case    QGraphicsPolygonItem::Type: //梯形和三角形
      {
        QGraphicsPolygonItem *theItem=qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
        setBrushColor(theItem);
        break;
      }
      case    QGraphicsLineItem::Type: //直线，设置线条颜色
      {
        QGraphicsLineItem *theItem=qgraphicsitem_cast<QGraphicsLineItem*>(item);
//        setPenColor(theItem);
        QPen    pen=theItem->pen();
        QColor  color=theItem->pen().color();
        color=QColorDialog::getColor(color,this,"选择线条颜色");
        if (color.isValid())
        {
            pen.setColor(color);
            theItem->setPen(pen);
        }
        break;
      }
      case    QGraphicsTextItem::Type: //文字，设置字体
      {
        QGraphicsTextItem *theItem=qgraphicsitem_cast<QGraphicsTextItem*>(item);
//        setItemFont(theItem);
        QFont font=theItem->font();
        bool ok=false;
        font=QFontDialog::getFont(&ok,font,this,"设置字体");
        if (ok)
            theItem->setFont(font);
        break;
      }
    }
}
void MainWindow::on_keyPress(QKeyEvent *event)
{

}

void MainWindow::add_Circles()
{
    for(int i = 0;i<12;i++)
    {
        QGraphicsEllipseItem   *item=new QGraphicsEllipseItem();
        //QGraphicsEllipseItem   *item=new QGraphicsEllipseItem(-196+i*120,-15,30,30);
       // QGraphicsEllipseItem   *item=new QGraphicsEllipseItem(-164+i*120,-15,30,30);
        if(i<4)
           item->setRect(-228+i*120,-15,30,30);
        else if (i>=4&&i<8) {
           item->setRect(-196+(i%4)*120,-15,30,30);
        }
        else {
          item->setRect(-164+(i%4)*120,-15,30,30);
        }
//        item->setFlags(  QGraphicsItem::ItemIsMovable
//                       | QGraphicsItem::ItemIsSelectable
//                       | QGraphicsItem::ItemIsFocusable);
        item->setBrush(Qt::gray);

        item->setPos(0,0);
        ++seqNum;
        item->setData(seqNum,seqNum);


        scene->addItem(item);
        scene->clearSelection();
        item->setSelected(true);
    }
}
void MainWindow::add_Rects()
{
    for (int i = 0;i<4;i++) {


        QGraphicsRectItem   *item=new QGraphicsRectItem(-230+i*120,-20,100,40);//x,y 为左上角的图元局部坐标，图元中心点为0,0
//        item->setFlags(QGraphicsItem::ItemIsMovable
//                       | QGraphicsItem::ItemIsSelectable
//                       | QGraphicsItem::ItemIsFocusable);
        item->setBrush(QBrush("#272830"));

        item->setPos(0,0);
//        ++seqNum;
//        item->setData(seqNum,seqNum);

        scene->addItem(item);
        scene->clearSelection();
        item->setSelected(true);

}
}
void MainWindow::add_Polygon()
{
         QPolygonF   points;
         points.append(QPointF(0,0));
         points.append(QPointF(-10,10));
         points.append(QPointF(-3,10));
         points.append(QPointF(-3,20));
         points.append(QPointF(3,20));
         points.append(QPointF(3,10));
         points.append(QPointF(10,10));

        for(int i = 0;i<12;i++)
          {
            QGraphicsPolygonItem   *item=new QGraphicsPolygonItem;
            item->setPolygon(points) ;

            if(i<4)
                {
                  item->setRotation(-90);
                  item->setPos(-225+(i%4)*120,0);
               }
            else if (i>=4&&i<8) {
               item->setRotation(0);
               item->setPos(-181+(i%4)*120,-10);
            }
            else {
              item->setRotation(90);
              item->setPos(-138+(i%4)*120,0);
            }

//            item->setFlags(QGraphicsItem::ItemIsMovable
//                           | QGraphicsItem::ItemIsSelectable
//                           | QGraphicsItem::ItemIsFocusable);

            scene->addItem(item);
            scene->clearSelection();
            item->setSelected(true);
      }

}

void MainWindow::add_Text()
{

        for(int i = 0;i < 4;i++)
        {
            QGraphicsTextItem   *item=new QGraphicsTextItem();
            switch (i) {
                case 0:item->setPlainText("东");  break;
                case 1:item->setPlainText("南");  break;
                case 2:item->setPlainText("西");  break;
                case 3:item->setPlainText("北");  break;
            }
            QFont   font=this->font();
            font.setPointSize(20);
            font.setBold(true);
            item->setFont(font);
//            item->setFlags(QGraphicsItem::ItemIsMovable
//                           | QGraphicsItem::ItemIsSelectable
//                           | QGraphicsItem::ItemIsFocusable);
            item->setPos(-200+i*120,-55);
            scene->addItem(item);
            scene->clearSelection();
            item->setSelected(true);

        }

}
